import React, { useState, useEffect, useRef } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
import { Progress } from './ui/progress';
import { Volume2, VolumeX, Play, Pause, Clock, Trophy, Star, CheckCircle } from 'lucide-react';
import { motion, AnimatePresence } from 'motion/react';
import { TestResult } from '../types';

interface AudioMemoryTestProps {
  onComplete: (result: TestResult) => void;
}

interface AudioSequence {
  id: number;
  frequency: number;
  duration: number;
  name: string;
  color: string;
}

// 音频音调定义
const AUDIO_TONES: AudioSequence[] = [
  { id: 1, frequency: 261.63, duration: 500, name: 'Do', color: 'bg-red-500' },
  { id: 2, frequency: 293.66, duration: 500, name: 'Re', color: 'bg-orange-500' },
  { id: 3, frequency: 329.63, duration: 500, name: 'Mi', color: 'bg-yellow-500' },
  { id: 4, frequency: 349.23, duration: 500, name: 'Fa', color: 'bg-green-500' },
  { id: 5, frequency: 392.00, duration: 500, name: 'Sol', color: 'bg-blue-500' },
  { id: 6, frequency: 440.00, duration: 500, name: 'La', color: 'bg-indigo-500' },
  { id: 7, frequency: 493.88, duration: 500, name: 'Si', color: 'bg-purple-500' }
];

export function AudioMemoryTest({ onComplete }: AudioMemoryTestProps) {
  const [stage, setStage] = useState<'instructions' | 'familiarize' | 'ready-check' | 'test' | 'results'>('instructions');
  const [currentLevel, setCurrentLevel] = useState(1);
  const [sequence, setSequence] = useState<AudioSequence[]>([]);
  const [userSequence, setUserSequence] = useState<AudioSequence[]>([]);
  const [isPlaying, setIsPlaying] = useState(false);
  const [showingSequence, setShowingSequence] = useState(false);
  const [score, setScore] = useState(0);
  const [lives, setLives] = useState(3);
  const [testComplete, setTestComplete] = useState(false);
  const [audioEnabled, setAudioEnabled] = useState(false);
  const [audioError, setAudioError] = useState<string>('');
  const [startTime, setStartTime] = useState<number>(0);
  const [familiarizeClicks, setFamiliarizeClicks] = useState(0);
  const [readyToStart, setReadyToStart] = useState(false);
  
  const audioContextRef = useRef<AudioContext>();
  const oscillatorRef = useRef<OscillatorNode>();

  const MAX_LEVEL = 10;
  const MIN_FAMILIARIZE_CLICKS = 10; // 至少需要点击10次才能进入测试

  useEffect(() => {
    return () => {
      if (oscillatorRef.current) {
        try {
          oscillatorRef.current.stop();
        } catch (e) {
          // 忽略错误
        }
      }
      if (audioContextRef.current && audioContextRef.current.state !== 'closed') {
        audioContextRef.current.close();
      }
    };
  }, []);

  const initializeAudio = async (): Promise<boolean> => {
    try {
      if (!audioContextRef.current) {
        audioContextRef.current = new (window.AudioContext || (window as any).webkitAudioContext)();
      }

      if (audioContextRef.current.state === 'suspended') {
        await audioContextRef.current.resume();
      }

      setAudioEnabled(true);
      setAudioError('');
      return true;
    } catch (error) {
      console.error('音频初始化失败:', error);
      setAudioError('音频初始化失败，请检查浏览器设置或尝试刷新页面');
      return false;
    }
  };

  const playTone = async (tone: AudioSequence): Promise<void> => {
    if (!audioContextRef.current || !audioEnabled) return;

    return new Promise((resolve, reject) => {
      try {
        if (oscillatorRef.current) {
          try {
            oscillatorRef.current.stop();
          } catch (e) {
            // 忽略错误
          }
        }

        const oscillator = audioContextRef.current!.createOscillator();
        const gainNode = audioContextRef.current!.createGain();
        
        oscillator.connect(gainNode);
        gainNode.connect(audioContextRef.current!.destination);
        
        oscillator.frequency.value = tone.frequency;
        oscillator.type = 'sine';
        
        const currentTime = audioContextRef.current!.currentTime;
        gainNode.gain.setValueAtTime(0, currentTime);
        gainNode.gain.linearRampToValueAtTime(0.3, currentTime + 0.01);
        gainNode.gain.exponentialRampToValueAtTime(0.01, currentTime + tone.duration / 1000);
        
        oscillator.start(currentTime);
        oscillator.stop(currentTime + tone.duration / 1000);
        
        oscillatorRef.current = oscillator;
        
        oscillator.onended = () => resolve();
        setTimeout(() => resolve(), tone.duration + 50); // 备用超时
      } catch (error) {
        console.error('播放音调失败:', error);
        reject(error);
      }
    });
  };

  const generateSequence = (length: number): AudioSequence[] => {
    const newSequence = [];
    for (let i = 0; i < length; i++) {
      const randomTone = AUDIO_TONES[Math.floor(Math.random() * AUDIO_TONES.length)];
      newSequence.push(randomTone);
    }
    return newSequence;
  };

  const playSequence = async (seq: AudioSequence[]) => {
    if (!audioEnabled) {
      const success = await initializeAudio();
      if (!success) return;
    }

    setIsPlaying(true);
    setShowingSequence(true);
    
    try {
      // 播放前等待一下
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      for (let i = 0; i < seq.length; i++) {
        await playTone(seq[i]);
        await new Promise(resolve => setTimeout(resolve, 400)); // 音符间隔
      }
    } catch (error) {
      console.error('播放序列失败:', error);
      setAudioError('音频播放失败，请检查音量设置');
    } finally {
      setShowingSequence(false);
      setIsPlaying(false);
    }
  };

  const handleFamiliarizeToneClick = async (tone: AudioSequence) => {
    if (isPlaying) return;
    
    await playTone(tone);
    setFamiliarizeClicks(prev => prev + 1);
  };

  const handleTestToneClick = async (tone: AudioSequence) => {
    if (isPlaying || showingSequence) return;

    await playTone(tone);
    
    const newUserSequence = [...userSequence, tone];
    setUserSequence(newUserSequence);

    // 检查答案
    const isCorrect = sequence[newUserSequence.length - 1].id === tone.id;
    
    if (!isCorrect) {
      // 错误
      setLives(prev => prev - 1);
      setUserSequence([]);
      
      if (lives <= 1) {
        setTestComplete(true);
        setStage('results');
      } else {
        // 重新播放序列
        setTimeout(() => {
          playSequence(sequence);
        }, 1000);
      }
    } else if (newUserSequence.length === sequence.length) {
      // 完成当前关卡
      const levelScore = currentLevel * 10 + (lives * 5);
      setScore(prev => prev + levelScore);
      
      if (currentLevel >= MAX_LEVEL) {
        setTestComplete(true);
        setStage('results');
      } else {
        // 下一关
        const nextLevel = currentLevel + 1;
        setCurrentLevel(nextLevel);
        setUserSequence([]);
        
        setTimeout(() => {
          const newSequence = generateSequence(Math.min(2 + nextLevel, 12)); // 从3个音符开始，最多12个
          setSequence(newSequence);
          playSequence(newSequence);
        }, 1500);
      }
    }
  };

  const handleStartFamiliarize = async () => {
    const success = await initializeAudio();
    if (!success) {
      return;
    }
    setStage('familiarize');
  };

  const handleReadyCheck = () => {
    if (familiarizeClicks >= MIN_FAMILIARIZE_CLICKS) {
      setStage('ready-check');
    }
  };

  const handleStartTest = () => {
    setStage('test');
    setStartTime(Date.now());
    setReadyToStart(true);
    const initialSequence = generateSequence(3);
    setSequence(initialSequence);
    
    setTimeout(() => {
      playSequence(initialSequence);
    }, 1000);
  };

  const handleComplete = () => {
    const maxPossibleScore = MAX_LEVEL * 15 * 3; // 每关最高分 * 关卡数 * 最大生命值
    const finalScore = Math.min(100, Math.round((score / maxPossibleScore) * 100));
    const actualDuration = startTime > 0 ? Math.round((Date.now() - startTime) / 1000) : 0;
    
    const result: TestResult = {
      id: Date.now().toString(),
      testType: 'audio-memory',
      score: finalScore,
      completedAt: new Date(),
      duration: actualDuration,
      details: {
        levelReached: currentLevel,
        totalScore: score,
        livesRemaining: lives,
        sequencesCompleted: currentLevel - 1,
        maxSequenceLength: Math.min(2 + currentLevel, 12),
        audioMemorySpan: currentLevel > 1 ? currentLevel + 1 : 3,
        accuracyRate: currentLevel > 1 ? Math.round(((currentLevel - 1) / MAX_LEVEL) * 100) : 0,
        familiarizeClicks: familiarizeClicks
      }
    };

    onComplete(result);
  };

  if (stage === 'instructions') {
    return (
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="max-w-2xl mx-auto"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-indigo-200 shadow-lg">
          <CardHeader className="text-center pb-8">
            <div className="w-16 h-16 bg-gradient-to-br from-indigo-500 to-purple-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg">
              <Volume2 className="w-8 h-8 text-white" />
            </div>
            <CardTitle className="text-2xl text-slate-800">音频记忆测试</CardTitle>
            <p className="text-slate-600 mt-2">测试您的纯听觉记忆能力</p>
          </CardHeader>
          
          <CardContent className="space-y-6">
            <div className="bg-gradient-to-r from-indigo-50 to-purple-50 rounded-xl p-6 border border-indigo-100">
              <h3 className="font-semibold text-indigo-900 mb-4 flex items-center gap-2">
                <Star className="w-5 h-5" />
                测试说明
              </h3>
              <div className="space-y-3 text-slate-700">
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-indigo-500 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">1</span>
                  <p>首先您需要熟悉7个不同的音符（Do、Re、Mi、Fa、Sol、La、Si）</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-indigo-500 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">2</span>
                  <p><strong>重要：</strong>这是纯音频记忆测试，播放时不会有任何视觉提示</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-indigo-500 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">3</span>
                  <p>系统播放音符序列后，您需要凭记忆重复相同的序列</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-indigo-500 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">4</span>
                  <p>序列长度会逐渐增加，您有3次错误机会</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-indigo-500 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">5</span>
                  <p>请确保音量适中，强烈建议佩戴耳机</p>
                </div>
              </div>
            </div>

            <div className="bg-amber-50 border border-amber-200 rounded-xl p-4">
              <div className="flex items-start gap-3">
                <Volume2 className="w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5" />
                <div className="text-amber-800">
                  <p className="font-semibold">注意事项：</p>
                  <p className="text-sm mt-1">这是纯音频记忆测试，请依靠听觉进行记忆，不要依赖任何视觉线索。</p>
                </div>
              </div>
            </div>

            <div className="grid md:grid-cols-3 gap-4">
              <div className="text-center p-4 bg-gradient-to-br from-indigo-50 to-indigo-100 rounded-xl border border-indigo-200">
                <div className="text-2xl font-bold text-indigo-600 mb-1">10</div>
                <div className="text-sm text-indigo-700">最大关卡</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-purple-50 to-purple-100 rounded-xl border border-purple-200">
                <div className="text-2xl font-bold text-purple-600 mb-1">3</div>
                <div className="text-sm text-purple-700">错误机会</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-indigo-50 to-purple-50 rounded-xl border border-indigo-200">
                <div className="text-2xl font-bold text-slate-600 mb-1">7</div>
                <div className="text-sm text-slate-700">音符种类</div>
              </div>
            </div>

            <Button 
              onClick={handleStartFamiliarize}
              className="w-full bg-gradient-to-r from-indigo-500 to-purple-500 hover:from-indigo-600 hover:to-purple-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
              size="lg"
            >
              开始熟悉音符
            </Button>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  if (stage === 'familiarize') {
    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-4xl mx-auto space-y-6"
      >
        {/* 顶部状态栏 */}
        <div className="flex flex-col sm:flex-row gap-4 items-center justify-between">
          <div className="flex items-center gap-4">
            <Badge variant="outline" className="bg-indigo-100 text-indigo-700 border-indigo-300">
              熟悉阶段
            </Badge>
            <div className="flex items-center gap-2 text-slate-600">
              <Volume2 className="w-4 h-4" />
              <span className="font-semibold">{familiarizeClicks} 次点击</span>
            </div>
          </div>
          
          <div className="flex items-center gap-4">
            {familiarizeClicks >= MIN_FAMILIARIZE_CLICKS ? (
              <Badge className="bg-green-100 text-green-700 border-green-300">
                <CheckCircle className="w-3 h-3 mr-1" />
                可以开始测试
              </Badge>
            ) : (
              <Badge variant="outline" className="bg-amber-100 text-amber-700 border-amber-300">
                还需 {MIN_FAMILIARIZE_CLICKS - familiarizeClicks} 次点击
              </Badge>
            )}
          </div>
        </div>

        {/* 熟悉进度 */}
        <div className="bg-white rounded-lg p-4 border border-slate-200">
          <div className="flex justify-between items-center mb-2">
            <span className="text-sm text-slate-600">熟悉进度</span>
            <span className="text-sm font-semibold text-slate-800">{Math.min(100, Math.round((familiarizeClicks / MIN_FAMILIARIZE_CLICKS) * 100))}%</span>
          </div>
          <Progress value={Math.min(100, (familiarizeClicks / MIN_FAMILIARIZE_CLICKS) * 100)} className="h-2" />
        </div>

        {/* 音符按钮 */}
        <Card className="bg-white/90 backdrop-blur-sm border-indigo-200 shadow-lg">
          <CardHeader>
            <CardTitle className="text-center">点击音符熟悉它们的声音</CardTitle>
            <p className="text-center text-slate-600 text-sm">
              请仔细聆听每个音符的声音，记住它们的音调特征
            </p>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-4 md:grid-cols-7 gap-4 max-w-2xl mx-auto">
              {AUDIO_TONES.map((tone) => (
                <motion.div
                  key={tone.id}
                  whileHover={{ scale: 1.05 }}
                  whileTap={{ scale: 0.95 }}
                >
                  <Button
                    onClick={() => handleFamiliarizeToneClick(tone)}
                    disabled={isPlaying}
                    className={`w-16 h-16 rounded-full ${tone.color} hover:opacity-80 text-white font-semibold shadow-lg transition-all duration-200`}
                  >
                    {tone.name}
                  </Button>
                </motion.div>
              ))}
            </div>

            {/* 错误提示 */}
            {audioError && (
              <div className="mt-4 p-3 bg-red-50 border border-red-200 rounded-lg">
                <div className="flex items-center gap-2">
                  <VolumeX className="w-4 h-4 text-red-600" />
                  <span className="text-red-800 text-sm">{audioError}</span>
                </div>
              </div>
            )}

            {/* 继续按钮 */}
            {familiarizeClicks >= MIN_FAMILIARIZE_CLICKS && (
              <div className="mt-6 text-center">
                <Button
                  onClick={handleReadyCheck}
                  className="bg-gradient-to-r from-green-500 to-emerald-500 hover:from-green-600 hover:to-emerald-600 text-white px-8 py-2"
                >
                  我已熟悉，准备测试
                </Button>
              </div>
            )}
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  if (stage === 'ready-check') {
    return (
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="max-w-2xl mx-auto"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-green-200 shadow-lg">
          <CardHeader className="text-center pb-8">
            <div className="w-16 h-16 bg-gradient-to-br from-green-500 to-emerald-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg">
              <CheckCircle className="w-8 h-8 text-white" />
            </div>
            <CardTitle className="text-2xl text-slate-800">准备开始测试</CardTitle>
            <p className="text-slate-600 mt-2">您已经熟悉了所有音符</p>
          </CardHeader>
          
          <CardContent className="space-y-6">
            <div className="bg-gradient-to-r from-green-50 to-emerald-50 rounded-xl p-6 border border-green-100">
              <h3 className="font-semibold text-green-900 mb-4 flex items-center gap-2">
                <Volume2 className="w-5 h-5" />
                测试提醒
              </h3>
              <div className="space-y-3 text-slate-700">
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-green-500 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">1</span>
                  <p>测试开始后，系统会播放音符序列（<strong>无视觉提示</strong>）</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-green-500 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">2</span>
                  <p>播放结束后，请凭记忆点击相同的音符序列</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-green-500 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">3</span>
                  <p>依次点击音符，顺序必须完全正确</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-green-500 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">4</span>
                  <p>错误时会重新播放序列，您有3次机会</p>
                </div>
              </div>
            </div>

            <div className="bg-red-50 border border-red-200 rounded-xl p-4">
              <div className="flex items-start gap-3">
                <VolumeX className="w-5 h-5 text-red-600 flex-shrink-0 mt-0.5" />
                <div className="text-red-800">
                  <p className="font-semibold">重要：纯音频测试</p>
                  <p className="text-sm mt-1">测试过程中不会有任何视觉高亮或提示，请完全依靠听觉记忆。</p>
                </div>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <Button
                onClick={() => setStage('familiarize')}
                variant="outline"
                className="py-3"
              >
                返回熟悉
              </Button>
              <Button 
                onClick={handleStartTest}
                className="bg-gradient-to-r from-green-500 to-emerald-500 hover:from-green-600 hover:to-emerald-600 text-white py-3 font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
              >
                开始正式测试
              </Button>
            </div>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  if (stage === 'test') {
    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-4xl mx-auto space-y-6"
      >
        {/* 顶部状态栏 */}
        <div className="flex flex-col sm:flex-row gap-4 items-center justify-between">
          <div className="flex items-center gap-4">
            <Badge variant="outline" className="bg-indigo-100 text-indigo-700 border-indigo-300">
              关卡 {currentLevel} / {MAX_LEVEL}
            </Badge>
            <div className="flex items-center gap-2 text-slate-600">
              <Trophy className="w-4 h-4" />
              <span className="font-semibold">{score} 分</span>
            </div>
          </div>
          
          <div className="flex items-center gap-4">
            <div className="flex gap-1">
              {Array.from({ length: 3 }).map((_, i) => (
                <div
                  key={i}
                  className={`w-3 h-3 rounded-full ${
                    i < lives ? 'bg-red-500' : 'bg-slate-200'
                  }`}
                />
              ))}
            </div>
            <span className="text-sm text-slate-600">生命</span>
          </div>
        </div>

        {/* 序列长度进度 */}
        <div className="bg-white rounded-lg p-4 border border-slate-200">
          <div className="flex justify-between items-center mb-2">
            <span className="text-sm text-slate-600">序列长度</span>
            <span className="text-sm font-semibold text-slate-800">{sequence.length} 音符</span>
          </div>
          <Progress value={(userSequence.length / sequence.length) * 100} className="h-2" />
        </div>

        {/* 播放状态指示 */}
        {(isPlaying || showingSequence) && (
          <Card className="bg-gradient-to-r from-indigo-50 to-purple-50 border-indigo-200">
            <CardContent className="py-4">
              <div className="flex items-center justify-center gap-3">
                <Volume2 className="w-5 h-5 text-indigo-600 animate-pulse" />
                <span className="text-indigo-800 font-semibold">
                  正在播放音符序列... 请仔细聆听
                </span>
              </div>
              <div className="text-center text-sm text-indigo-600 mt-1">
                （无视觉提示，请依靠听觉记忆）
              </div>
            </CardContent>
          </Card>
        )}

        {/* 音符按钮 - 纯色版本，无视觉提示 */}
        <Card className="bg-white/90 backdrop-blur-sm border-indigo-200 shadow-lg">
          <CardHeader>
            <CardTitle className="text-center">点击重复刚才听到的序列</CardTitle>
            <p className="text-center text-slate-600 text-sm">
              请按照听到的顺序点击音符
            </p>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-4 md:grid-cols-7 gap-4 max-w-2xl mx-auto">
              {AUDIO_TONES.map((tone) => (
                <motion.div
                  key={tone.id}
                  whileHover={{ scale: 1.05 }}
                  whileTap={{ scale: 0.95 }}
                >
                  <Button
                    onClick={() => handleTestToneClick(tone)}
                    disabled={isPlaying || showingSequence}
                    className={`w-16 h-16 rounded-full ${tone.color} hover:opacity-80 text-white font-semibold shadow-lg transition-all duration-200`}
                  >
                    {tone.name}
                  </Button>
                </motion.div>
              ))}
            </div>

            {/* 用户输入序列显示 */}
            {userSequence.length > 0 && (
              <div className="mt-6">
                <h3 className="text-sm font-semibold text-slate-600 mb-3 text-center">您的输入：</h3>
                <div className="flex justify-center gap-2 flex-wrap">
                  {userSequence.map((tone, index) => (
                    <div
                      key={`${tone.id}-${index}`}
                      className={`w-8 h-8 rounded-full ${tone.color} flex items-center justify-center text-white text-xs font-semibold shadow`}
                    >
                      {tone.name}
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* 错误提示 */}
            {audioError && (
              <div className="mt-4 p-3 bg-red-50 border border-red-200 rounded-lg">
                <div className="flex items-center gap-2">
                  <VolumeX className="w-4 h-4 text-red-600" />
                  <span className="text-red-800 text-sm">{audioError}</span>
                </div>
              </div>
            )}

            {/* 重新播放按钮 */}
            {!isPlaying && !showingSequence && sequence.length > 0 && (
              <div className="mt-4 text-center">
                <Button
                  onClick={() => playSequence(sequence)}
                  variant="outline"
                  size="sm"
                  className="text-indigo-600 border-indigo-300 hover:bg-indigo-50"
                >
                  <Play className="w-4 h-4 mr-2" />
                  重新播放序列
                </Button>
              </div>
            )}
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  if (stage === 'results') {
    const maxPossibleScore = MAX_LEVEL * 15 * 3; // 每关最高分 * 关卡数 * 最大生命值
    const finalScore = Math.min(100, Math.round((score / maxPossibleScore) * 100));

    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-2xl mx-auto"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-indigo-200 shadow-xl">
          <CardHeader className="text-center pb-6">
            <motion.div
              initial={{ scale: 0 }}
              animate={{ scale: 1 }}
              transition={{ delay: 0.2, type: "spring", stiffness: 200 }}
              className="w-20 h-20 bg-gradient-to-br from-indigo-500 to-purple-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg"
            >
              <Trophy className="w-10 h-10 text-white" />
            </motion.div>
            
            <CardTitle className="text-3xl text-slate-800 mb-2">测试完成！</CardTitle>
            <div className="text-6xl font-bold bg-gradient-to-r from-indigo-500 to-purple-500 bg-clip-text text-transparent">
              {finalScore}
            </div>
            <p className="text-slate-600">音频记忆能力得分</p>
          </CardHeader>
          
          <CardContent className="space-y-6">
            <div className="grid grid-cols-2 gap-4">
              <div className="text-center p-4 bg-gradient-to-br from-indigo-50 to-indigo-100 rounded-xl border border-indigo-200">
                <div className="text-2xl font-bold text-indigo-600 mb-1">{currentLevel}</div>
                <div className="text-sm text-indigo-700">到达关卡</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-purple-50 to-purple-100 rounded-xl border border-purple-200">
                <div className="text-2xl font-bold text-purple-600 mb-1">{score}</div>
                <div className="text-sm text-purple-700">总分数</div>
              </div>
            </div>

            <div className="space-y-3">
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <span className="text-slate-600">最长序列</span>
                <span className="font-semibold text-slate-800">{Math.min(2 + currentLevel, 12)} 音符</span>
              </div>
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <span className="text-slate-600">音频记忆广度</span>
                <span className="font-semibold text-slate-800">{currentLevel > 1 ? currentLevel + 1 : 3} 音符</span>
              </div>
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <span className="text-slate-600">完成率</span>
                <span className="font-semibold text-slate-800">
                  {currentLevel > 1 ? Math.round(((currentLevel - 1) / MAX_LEVEL) * 100) : 0}%
                </span>
              </div>
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <span className="text-slate-600">熟悉点击次数</span>
                <span className="font-semibold text-slate-800">{familiarizeClicks} 次</span>
              </div>
            </div>

            <Button 
              onClick={handleComplete}
              className="w-full bg-gradient-to-r from-indigo-500 to-purple-500 hover:from-indigo-600 hover:to-purple-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
              size="lg"
            >
              查看详细结果
            </Button>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  return null;
}